<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :defaultFullscreen="true"
    :destroyOnClose="true"
    title="二维表登记"
    :width="1200"
    @ok="handleSave"
    :showOkBtn="!isView"
    :okButtonProps="{
      loading: okLoading,
    }"
  >
    <!--引用表格-->
    <div class="table-content table-width">
      <!-- <BasicForm @register="registerForm" /> -->
      <BasicTable @register="registerCustomTable">
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.editRow && column.editComponent === 'InputNumber'">
            <a-input-number
              :disabled="isView"
              v-model:value="record[column['dataIndex']]"
              @change="scoreCompute(record)"
              @focus="handleIndex(index)"
            />
          </template>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>

<script lang="ts" name="com.hzzenith.km.emp-hubTeamAdd" setup>
  import { ref } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { twoColumns } from './HubTeamResultWork.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getTwoColumn, save } from './HubTeamResultWork.api';
  import { getBaseRelList } from '/@/api/common/api';
  import { unifyNumber } from '/@/views/zhc/util/numUtils';
  import dayjs from 'dayjs';

  // 轻提醒
  const { createMessage: $message } = useMessage();
  // Emits声明
  const emit = defineEmits(['register', 'success']);

  let pageParams = {};
  let editid = null;
  const okLoading = ref(false);
  let isView = ref(false);
  const twoForm = [
    {
      field: 'endDate',
      label: '工作时间',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      defaultValue: dayjs(),
      required: true,
      dynamicDisabled: () => isView.value,
      colProps: { span: 12 },
    },
  ];
  //表单配置
  // const [registerForm, { setFieldsValue = () => {}, getFieldsValue = () => {}, resetSchema = () => {} }] = useForm({
  //   schemas: twoForm,
  //   showActionButtonGroup: false,
  // });

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    okLoading.value = false;
    pageParams = { ...data };
    editid = data.isEdit ? data.res.id : null;
    isView.value = data.isView;
    getTableColumn({ ...data });
    if (data.isEdit) {
      // 编辑状态
      getForm().setFieldsValue({
        endDate: dayjs(data.res.endDate),
      });
      let tableData = data.res.details || [];
      tableData = tableData.map((item) => {
        if (item.reamrk) {
          return {
            ...item,
            ...JSON.parse(item.reamrk),
          };
        }
      });
      console.log('tableData', tableData);
      setTableData(tableData);
    } else {
      reload({
        searchInfo: {
          orgCode: pageParams.orgCode,
          periodCode: pageParams.periodCode,
        },
      });
    }
  });

  const handleCancel = () => {
    console.log('取消');
  };

  const handleSave = () => {
    let formData = getForm().getFieldsValue();
    let tableData = getDataSource();
    let saveData = {
      addMode: '30',
      details: tableData,
      orgCode: pageParams.orgCode,
      orgName: pageParams.orgName,
      periodCode: pageParams.periodCode,
      psnName: '全部人员',
      endDate: dayjs(formData.endDate).format('YYYY-MM-DD'),
    };
    saveData.details?.forEach((item) => {
      let sumScore = 0;
      item.reamrk = {};
      Object.keys(item).forEach((key) => {
        if (key.indexOf('IPP') != -1) {
          sumScore += item[key];
          item.reamrk = {
            ...item.reamrk,
            [key]: item[key],
            sumPoints: sumScore,
          };
        }
        item.sumPoints = sumScore;
      });
    });
    saveData.details?.forEach((item) => {
      if (item.reamrk) {
        item.reamrk = JSON.stringify(item.reamrk);
      }
    });
    if (editid) {
      saveData.id = editid;
    }
    okLoading.value = true;
    save(saveData).then((res) => {
      if (res) {
        //关闭弹窗
        closeModal();
        okLoading.value = false;
        //刷新列表
        emit('success');
      }
    });
    console.log('保存', saveData);
  };

  // 动态表头
  const getTableColumn = async (params) => {
    console.log('获取详情动态表头');
    // detailTableRef.value?.setColumns(columns);
    let newColumn = JSON.parse(JSON.stringify(twoColumns));
    console.log('1111newColumn', newColumn);
    getTwoColumn(params).then((res) => {
      console.log('获取详情动态表头', res);
      res.forEach((r) => {
        let temp = {
          title: r.headName,
        };
        //多级表头处理
        let childList = r.children;
        if (childList) {
          //有子列表情况
          let newChildList = [];
          childList.forEach((r1) => {
            let childTemp = {
              title: r1.headName,
              dataIndex: r1.headCode,
              width: 160,
              align: 'center',
              editRow: true,
              editComponent: 'InputNumber',
            };
            newChildList.splice(newChildList.length, 0, { ...childTemp });
          });
          temp['children'] = newChildList;
        }
        newColumn.splice(newColumn.length - 1, 0, {
          ...temp,
        });
      });
      nextTick(() => {
        setColumns(newColumn);
      });
    });
  };

  //注册table数据
  const { prefixCls, tableContext, onImportXls } = useListPage({
    tableProps: {
      // title: 'hub_team_add',
      api: getBaseRelList,
      columns: twoColumns,
      canResize: false,
      // dataSource: [],
      showIndexColumn: true,
      showActionColumn: false,
      rowKey: 'id',
      sticky: true,
      beforeFetch: (params) => {
        return Object.assign(params, {});
      }, //表格和查询条件同步更新的方法
      afterFetch: (list) => {
        list = list.map((item) => {
          return {
            addMode: '30',
            orgCode: item.orgCode,
            orgName: item.orgName,
            psnName: item.psnName,
            psnNum: item.psnNum,
          };
        });
        console.log('11```', list);
        return list;
      },
      formConfig: {
        //labelWidth: 120,
        schemas: twoForm,
        autoSubmitOnEnter: true,
        showAdvancedButton: false,
        fieldMapToNumber: [],
        fieldMapToTime: [],
        showResetButton: false,
        showSubmitButton: false,
        // resetButtonOptions: {
        //   text: '取消',
        // },
        // submitFunc: handleSave,
        // resetFunc: handleCancel,
      },
      immediate: false, // 班组表格放到orgCode拿到值之后再加载 false不会立即加载,reload()之后再加载
      pagination: false,
    },
  });

  const [registerCustomTable, { getForm, reload, getDataSource, setColumns, getColumns, setTableData }] = tableContext;

  let currentTableIndex = 0; //记录当前操作的表格数据行

  const handleIndex = (index) => {
    currentTableIndex = index;
  };

  const scoreCompute = (record) => {
    // let tableData = getDataSource();
    // let currentRecord = tableData[currentTableIndex];
    console.log('record', record);
    let sum = 0;
    Object.keys(record).forEach((key) => {
      if (key.indexOf('IPP') != -1 && record[key]) {
        sum += record[key];
      }
    });
    record.sumPoints = unifyNumber(sum);
  };
</script>

<style scoped lang="less">
  .treeBox {
    margin: 10px 0 0 8px;
    background-color: white;
    height: calc(100% - 20px);
    width: 270px;
  }

  .table-width {
    width: 100%;
    height: 70vh;
    overflow-y: scroll;
  }

  .treeTitle {
    margin-top: 10px;
    background-color: #009688;
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    font-size: 20px;
  }
</style>
